//
//  PFPhotoUploadViewController.m
//  PrintFamily
//
//  Created by edaihua on 16/3/19.
//  Copyright © 2016年 ___PrintFactory___. All rights reserved.
//

#import "PFPhotoUploadViewController.h"
#import "PFPhotoUploadCollectionViewCell.h"
#import "PFPhotoUploadCollectionViewLayout.h"
#import "PFPhotosManager.h"
#import "PFPhoto.h"
#import "UIImage+Crop.h"
#import <QiniuSDK.h>

@import Photos;

@interface PFPhotoUploadViewController () <UICollectionViewDelegate, UICollectionViewDataSource>

@property (strong, nonatomic) PFPhotoUploadCollectionViewLayout *layout;

@property (strong, nonatomic) IBOutlet UIButton *leftButton;
@property (strong, nonatomic) IBOutlet UIButton *rightButton;

@property (strong, nonatomic) IBOutlet UICollectionView *photoCollectionView;

@property (strong, nonatomic) NSMutableArray *progressLabelArray;

@property (atomic) NSUInteger uploadingIndex;

@property (nonatomic, strong) QNUploadManager *upManager;

@end

@implementation PFPhotoUploadViewController
@synthesize upManager = _upManager;

static NSString * const reuseIdentifier = @"UploadCell";

- (void)viewDidLoad {
    [super viewDidLoad];
    
    if (self.layout == nil) {
        self.layout = [[PFPhotoUploadCollectionViewLayout alloc] init];
        [self.photoCollectionView setCollectionViewLayout:self.layout];
    }
    
    [self.photoCollectionView registerClass:[PFPhotoUploadCollectionViewCell class] forCellWithReuseIdentifier:reuseIdentifier];
    self.photoCollectionView.delegate = self;
    self.photoCollectionView.dataSource = self;
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:self.rightButton];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:self.leftButton];
    
    self.progressLabelArray = [[NSMutableArray alloc] init];
    self.uploadingIndex = 0;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - UICollectionView DataSource/Delegate
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    NSLog(@"number of items: %lu", [self.photosManager getPhotoCount]);
    return [self.photosManager getPhotoCount];
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    PFPhotoUploadCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:reuseIdentifier forIndexPath:indexPath];
    
    CGFloat scale     = [UIScreen mainScreen].scale;
    CGSize  cellSize  = self.layout.itemSize;
    CGSize targetSize = CGSizeMake(cellSize.width * scale, cellSize.height * scale);
    
    void (^resultHandler)(UIImage*, NSDictionary*) = ^(UIImage * _Nullable result, NSDictionary * _Nullable info) {
        UIImage *croppedImage = [result getImageInCenterAtSize:targetSize];
        
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, cellSize.width, cellSize.height)];
        [imageView setImage:croppedImage];
        [imageView setContentMode:UIViewContentModeScaleToFill];
        
        cell.maskView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, cellSize.width, cellSize.height)];
        cell.maskView.alpha = 0.5;
        cell.maskView.backgroundColor = [UIColor blackColor];
        
        UIProgressView *progressView = [[UIProgressView alloc] initWithFrame:CGRectMake(0, cellSize.height - 20, cellSize.width, 20)];
        progressView.progress = 0;
        
        [self.progressLabelArray insertObject:progressView atIndex:indexPath.row];
        
        for (UIView *view in [cell.contentView subviews]) {
            [view removeFromSuperview];
        }
        
        
        [cell.contentView addSubview:imageView];
        [cell.contentView addSubview:progressView];
        
        [cell.contentView bringSubviewToFront:progressView];
        
    };
    
    PFPhoto *photo = [self.photosManager getPhotoAtIndex:indexPath.row];
    [[PHImageManager defaultManager] requestImageForAsset:photo.asset targetSize:targetSize contentMode:PHImageContentModeAspectFit options:nil resultHandler:resultHandler];
    
    return cell;
}

- (void)uploadPhotosWithToken:(NSString*)token {
    if (self.uploadingIndex < [self.photosManager getPhotoCount]) {
        
        NSString *key = [NSString stringWithFormat:@"xiaozhengfang_13761868036_321212_%ld.jpg", self.uploadingIndex];
        
        QNUploadOption *option = [[QNUploadOption alloc] initWithProgressHandler:^(NSString *key, float percent) {
            
            [self performSelectorOnMainThread:@selector(updateProgress:) withObject:[NSNumber numberWithFloat:percent] waitUntilDone:NO];
            NSLog(@"uploading percent: %f", percent);
        }];
        
        PFPhoto *photo = [self.photosManager getPhotoAtIndex:self.uploadingIndex];
        [self.upManager putPHAsset:photo.asset key:key token:token complete:^(QNResponseInfo *info, NSString *key, NSDictionary *resp) {
            
            UIProgressView *progressView = [self.progressLabelArray objectAtIndex:0];
            [progressView setProgress:1.0 animated:YES];
            
            ++self.uploadingIndex;
            [self uploadPhotosWithToken:token];
            NSLog(@"Upload complete!!");
            
        } option:option];
    }
}

- (void)updateProgress:(NSNumber*)percent {
    UIProgressView *progressView = [self.progressLabelArray objectAtIndex:self.uploadingIndex];
    [progressView setProgress:percent.floatValue animated:YES];
}

#pragma mark - Button gesture handling
- (IBAction)leftButtonTapped:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

// Right button is the upload button
- (IBAction)rightButtonTapped:(id)sender {
    
    [AppDelegate.engine requestUploadTokenOnSucceeded:^(id sender) {
        NSDictionary *response = sender;
        NSString *token = [response objectForKey:@"upload_token"];
         /*
        
        //NSData *data = [@"Hello Yinxin!" dataUsingEncoding:NSUTF8StringEncoding];
        
        NSString *key = @"xiaozhengfang_13761868036_321212_hello.jpg";
        
        QNUploadOption *option = [[QNUploadOption alloc] initWithProgressHandler:^(NSString *key, float percent) {
            
            [self performSelectorOnMainThread:@selector(updateProgress:) withObject:[NSNumber numberWithFloat:percent] waitUntilDone:NO];
            NSLog(@"uploading percent: %f", percent);
        }];
        
        [upManager putPHAsset:[[self.photosManager getPhotoAtIndex:0] getAsset] key:key token:token complete:^(QNResponseInfo *info, NSString *key, NSDictionary *resp) {
            
            UIProgressView *progressView = [self.progressLabelArray objectAtIndex:0];
            [progressView setProgress:1.0 animated:YES];
            NSDictionary *response = resp;
            NSLog(@"Upload complete!!");
            
        } option:option];
         */
        [self uploadPhotosWithToken:token];
    } onError:^(NSError *engineError) {
        
    }];
    
}

#pragma mark - synthethizer
- (QNUploadManager*)upManager {
    if (_upManager == nil) {
        _upManager = [[QNUploadManager alloc] init];
    }
    return _upManager;
}

@end
